//
//  OauthController.swift
//  WSWB
//
//  Created by 刘 伟生 on 16/1/11.
//  Copyright © 2016年 seasa. All rights reserved.
//

import UIKit

class OauthController: UIViewController {

    @IBOutlet weak var webView: UIWebView!

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置
        webView.delegate = self
        
        //首先加载网页view
        //1.1先拼接url
        let webStr = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        guard let webUrl = NSURL(string: webStr) else {
            return
        }
        
        //根据url,创建请求
        let request = NSURLRequest(URL: webUrl)
        
        //webView 加载网页
        webView.loadRequest(request)
        
        
        //创建webView上的左右按钮
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Done, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Done, target: self, action: "full")
    }
    
    //关闭webView
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //填充密码和用户名
    @objc private func full() {
        // 1.写js代码
//        let jsCode = "document.getElementById('userId').value='1606020376@qq.com';document.getElementById('passwd').value='haomage';"
        let jsCode = "document.getElementById('userId').value='1606020376@qq.com';document.getElementById('passwd').value='haomage';"

        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }

 
}


extension OauthController : UIWebViewDelegate {
    

    //每次请求都会调用该方法,如果返回false代表不允许发送新的请求, 如果返回true代表允许发送新的请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
        {
//           print(request)
            
            //打开授权页面: https://api.weibo.com/oauth2/authorize?client_id=1988376015&redirect_uri=http://www.520it.com
            
            //点击登陆:URL: https://api.weibo.com/oauth2/authorize 
            
            //点击授权:http://www.520it.com/?code=acf7b89ccea9877638f4b6655f999cd4 
            
            //已授权:https://api.weibo.com/oauth2/authorize?client_id=1988376015&redirect_uri=http://www.520it.com 
            
            //取消授权:http://www.520it.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
            
            //1.过滤非授权请求    同时值得注意的是where前后的条件真假性一直的时候才执行括号内的内容(if 中同时为真,guard中同时为假)
           guard let str = request.URL?.absoluteString where str.hasPrefix(redirect_uri)
            else
            {
                return true
            }
            
            //2.处理授权回调地址
            let code = "code="
            if let querystr = request.URL?.query where querystr.hasPrefix(code){
                //此时那么这个就是已授权的请求,去哦去授权的code
               let codeStr = querystr.substringFromIndex(code.endIndex)
                
                //利用已授权的request_token换取assess_token
                loadAssess_token(codeStr)
                return false
                
            }
            //关闭控制器
            close()
            return true
            
    }
    
    func loadAssess_token(request_token : String) {
        
        //准备URL路径
        let path = "oauth2/access_token"
        
        //创建请求参数
        let pragma = ["client_id" : app_key, "client_secret" : app_secret, "grant_type" : "authorization_code", "code" : request_token, "redirect_uri" : redirect_uri]

        // 3.利用AFN发送POST请求
        
        //发送请求
        NetWorkTool.shareInstance.POST(path, parameters: pragma, success: { (task, objc) -> Void in
            
            //在这里面进行数据存储和字典转模型
            
            //先获取数据
            guard let dict = objc as? [String : AnyObject] else {
                print("获取数据")
                return
            }
            
            
            
            //字典转模
            let account = UserCount(dict: dict)
            account.loadUserInfo({ (dict, error) -> () in
                //先判断下载是否出错
                if error != nil {
                    //下载失败
                    return
                }
                account.saveUserCount()
                
                print("获取用户数据成功")
                
                NSNotificationCenter.defaultCenter().postNotificationName(XMGChangeRootViewControllerNotification, object: nil, userInfo: ["message" : false])
                
            })
            
//            //将对象保存到文件中去
//            account.saveUserCount()
//            print(objc)
            
            }) { (task, error) -> Void in
                print("请求失败的原因是:\(error)")
        }
    }
    
}



